__author__ = 'tyrion'



from flask import  Flask
from flask import request


import  json
import  commands
# import  rrdtool
from  src.tools.rrdtool import *

app = Flask(__name__)



@app.route("/infrastructure/monitor/perdata", methods=['GET', 'POST'])
def GetInstancePerfData():
    #[{"server": "", "instances"[{"instance": "", "start":"", "end": ""}] }]
    data = request.get_data()
    print"info: request body = %s" %(data)
    servers = json.loads(data)
    print( servers)
    # print("info: json request body =%s") %servers

    # result = []
    ret = "ok"
    for server in servers:
        svrName = server.get("server", "error: not found server name")
        instances = server.get("instances", "error: not found instances")
        for instance in instances:
            instanceName = instance.get("instance", "error: not found instance name")
            starTime = instance.get("start", "error : not found start time")
            print(starTime)
            if starTime == "":
                starTime = "now-1day"
            endTime = instance.get("end", "error, not found end time")
            if endTime == "":
                endTime = "now"
            print(endTime)

            cmd = "rrdtool  fetch /usr/local/pnp4nagios/var/perfdata/%s/%s.rrd   AVERAGE -s %s  -e %s"%(svrName, instanceName, starTime, endTime)
            print("info:%s" %cmd)
            ret = commands.getoutput(cmd)
            # jsonRet = json.loads(ret)
            # print(jsonRet)

    # jsonResult = json.dumps(result)
    return ret


@app.route("/infrastructure/monitor/history", methods=['GET', 'POST'])
def GetInstanceStatusHistory():
    data = request.get_data()
    print"info: request body = %s" %(data)
    jsonData = json.loads(data)
    print( jsonData)

    instanceName = jsonData.get("instance", "error: not found instance name")
    serverName = jsonData.get("server", "error: not found server name")
    step = jsonData.get("step", "60")
    start = jsonData.get("start", "now-1d")
    print("info: start = %s"%start)
    end = jsonData.get("end", "now")
    print("info: end = %s"%(end))

    jsonRet = GetHistoryPerfData(instanceName, serverName, start, end, step)

    return jsonRet

if __name__ == "__main__":
    app.run(debug = True, host="0.0.0.0", port=5001)
